package br.com.divulgaqui.service;

import javax.annotation.PostConstruct;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;

import org.jboss.logging.Logger;

import br.com.divulgaqui.client.ContaServiceBeanLocal;
import br.com.divulgaqui.client.ContaServiceBeanRemote;
import br.com.divulgaqui.client.exception.LoginException;
import br.com.divulgaqui.client.exception.LoginInativoException;
import br.com.divulgaqui.entity.Pessoa;
import br.com.divulgaqui.persistence.dao.ContaDAO;
import br.com.divulgaqui.persistence.daoimpl.ContaDAOImpl;

/**
 * Session Bean implementation class ContaServiceBean
 */
@Stateless
public class ContaServiceBean implements ContaServiceBeanRemote, ContaServiceBeanLocal {
	
	@PersistenceContext
	private EntityManager entityManager;
	private ContaDAO contaDAO;
	private Logger logg = Logger.getLogger(ContaServiceBean.class);

    /**
     * Default constructor. 
     */
    public ContaServiceBean() {        
    }
    
    @PostConstruct
    public void init(){
    	contaDAO = new ContaDAOImpl(entityManager);
    }

	@Override
	public Pessoa login(String senha, String email) throws LoginException, LoginInativoException {
		Pessoa p = null;
		try {
			p = contaDAO.recuperarPessoa(senha,email);
			if(p == null){
				logg.warn("Login ou senha inválidos");
				throw new LoginException();
			}
			else if (!p.getAtivo()) {
				throw new LoginInativoException();
			}
		} catch (NoResultException e) {
			logg.warn("Login ou senha inválidos");
			throw new LoginException();
		}
		return p;
	}

}
